<?php

namespace app\common\model\fp;

use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use think\Model;
use think\model\concern\SoftDelete;
use Throwable;

/**
 * PostComments
 */
class PostComments extends Model
{
    use SoftDelete;

    protected string $deleteTime = 'delete_time';

    protected $defaultSoftDelete = 0;
    // 表名
    protected $name = 'fp_post_comments';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    protected $updateTime = false;

    const TABLE_NUM = 10;


    protected $type = [
        'id' => 'string',
    ];

    public function getIdAttr($value): string
    {
        return (string)$value;
    }


    protected static function onBeforeInsert($model): void
    {
        $pk = $model->getPk();
        $model->$pk = \app\common\library\SnowFlake::generateParticle();
    }

    /**
     * 如果表不存在，则创建新表
     *
     * @param string $tableName 要创建的表名
     * @return bool
     * @throws Throwable
     */
    public static function createTableIfNotExists(string $tableName): bool
    {
        $cacheKey = 'makeTable:' . $tableName;
        $check = Cache::get($cacheKey);
        if ($check) {
            return true;
        }

        // 检查表是否存在
        $exists = Db::query("SHOW TABLES LIKE  '{$tableName}'");

        if (!$exists) {
            $sql = <<<SQL
            CREATE TABLE `{$tableName}` (
              `id` bigint(20) unsigned NOT NULL COMMENT 'ID',
              `post_id` bigint(20) NOT NULL DEFAULT '0' COMMENT '动态ID',
              `parent_id` bigint(20) NOT NULL DEFAULT '0' COMMENT '回复id',
              `reply_user_id` bigint(20) NOT NULL COMMENT '回复评论的用户ID',
              `post_user_id` bigint(20) NOT NULL COMMENT '动态作者ID',
              `comment_user_id` bigint(20) NOT NULL DEFAULT '0' COMMENT '评论者ID',
              `content` varchar(500) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '评论内容',
              `status` tinyint(1) unsigned NOT NULL DEFAULT '1' COMMENT '状态:0=屏蔽,1=显示',
              `create_time` int(11) NOT NULL COMMENT '评论时间',
              `delete_time` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '删除时间',
              PRIMARY KEY (`id`),
              KEY `post_id` (`post_id`),
              KEY `reply_user_id` (`parent_id`),
              KEY `comment_user_id` (`comment_user_id`),
              KEY `post_user_id` (`post_user_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC COMMENT='动态-评论表';
        SQL;

            try {
                Db::execute($sql);
            } catch (Throwable $e) {
                // 记录异常信息
                Log::channel('my')->error("Failed to create table {$tableName}: " . $e->getMessage());
                // 可以选择抛出异常或返回错误信息
                throw new \RuntimeException("Failed to create table: " . $e->getMessage(), 0, $e);
            }

        }

        Cache::set($cacheKey, 1);

        return true;
    }

    /**
     * 获取分表表名
     * @param $userId
     * @param bool $hasPrefix
     * @return string
     */
    public static function getDbTableName($userId, bool $hasPrefix = false): string
    {
        $tableName = 'fp_post_comments_' . ($userId % self::TABLE_NUM);
        $prefix = '';
        if ($hasPrefix) {
            $prefix = config('database.connections.mysql.prefix');
        }
        return $prefix . $tableName;
    }

    /**
     * 实例化表
     * @param $postId
     * @return PostComments
     * @throws Throwable
     */
    public static function initModel($postId): static
    {
        $model = new static();
        $tableName = self::getDbTableName($postId);
        $model->setName($tableName);
        $tableName = self::getDbTableName($postId, true);
        self::createTableIfNotExists($tableName);
        return $model;
    }

}